<?php
namespace App\Pay\Gateway;

use App\Pay\Config\Config;
use App\Pay\Contracts\GatewayInterface;
use App\Pay\Exceptions\GatewayException;
use App\Pay\Exceptions\InvalidArgumentException;
use App\Pay\Exceptions\InvalidSignException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class Qqpay implements GatewayInterface
{

    /**
     * @var array
     */
    protected $payload = [];

    public function __construct(Config  $config)
    {
        $this->config = $config;
        \App\Pay\Gateway\Qqpay\Request::instance()->setConfig($this->config);
    }

    public function pay(string $endpoint, array $params)
    {
        $gatewayClass = get_class($this) . '\\' . ucfirst($endpoint) . 'Gateway';
        if (!class_exists($gatewayClass)) {
            throw new GatewayException('Gateway not defind');
        }
        $mchId = $this->config->get('mch_id', null);
        $mchKey = $this->config->get('mch_key', null);
        $notifyUrl = $this->config->get('notify_url', null);

        // 判断配置参数是否为空
        if (is_null($mchId) || is_null($mchKey) || is_null($notifyUrl)) {
            throw new InvalidArgumentException('Configuration error');
        }

        $this->payload = array_merge([
            'mch_id' => $this->config->get('mch_id'),
            'nonce_str' => uniqid(),
            'spbill_create_ip' => Request::createFromGlobals()->getClientIp(),
            'trade_type' => '',
            'notify_url' => $this->config->get('notify_url')
        ], $params);
        return (new $gatewayClass())->pay($this->payload);
    }

    public function cancel(array $params)
    {
        // TODO: Implement cancel() method.
    }

    public function close(array $params)
    {
        // TODO: Implement close() method.
    }

    public function query(array $params)
    {
        // TODO: Implement query() method.
    }

    public function refund(array $params)
    {
        // TODO: Implement refund() method.
    }

    public function refundQuery(array $params)
    {
        // TODO: Implement refundQuery() method.
    }

   public function verify($content = null, $isRefund = false)
   {
       $content = $content ?: Request::createFromGlobals()->getContent();
       $data = \App\Pay\Gateway\Qqpay\Request::xmlToArr($content);
       if (\App\Pay\Gateway\Qqpay\Request::sign($data) === $data['sign']) {
           return $data;
       }
       throw new InvalidSignException('签名错误');
   }

    public function success()
    {
        return new Response(
            \App\Pay\Gateway\Wechat\Request::arrToXml(['return_code' => 'SUCCESS']),
            200,
            ['Content-Type' => 'application/xml']
        );
    }
}
